import type {
  conversionPixelSizeFunction,
  debounceFunction,
  formatTimeRemainingFunction,
  getImageUrlFunction
} from '@renderer/types'
import dayJs from 'dayjs'
import mitt from 'mitt'

/**
 * 时间格式函数
 * @returns
 */
export const dayjs = dayJs

/**
 * 事件总线
 */
export const EventBus = mitt()

/**
 * 防抖
 * @param func 回调函数
 * @param wait 防抖时间
 * @returns 方法
 */
let timeout: number | NodeJS.Timeout
export const debounce: debounceFunction = (func: Function, wait = 1000) => {
  function _debounce() {
    timeout && clearTimeout(timeout)
    timeout = setTimeout(() => {
      func && typeof func === 'function' && func()
    }, wait)
  }
  _debounce()
}

/**
 * 动态导入图片
 * @param name 图片名称
 * @param type 文件后缀类型
 * @returns 图片文件
 */
export const getImageUrl: getImageUrlFunction = (name: string, type = 'png') => {
  const dirname = type === 'svg' ? 'icons' : 'images'
  return new URL(
    // 本地资源路径
    `/src/assets/${dirname}/${name}.${type}`,
    import.meta.url
  ).href
}

/**
 * px 转 rem
 * 默认是16px
 */
export const px2rem: conversionPixelSizeFunction = (size: number): string => {
  const rootSize = 16
  return `${(size / rootSize).toFixed(2)}rem`
}
/**
 * 时间戳转剩余时间
 * @param {Number} timestamp 时间戳
 * @returns 小时/分钟/秒/天
 */
export const formatTimeRemaining: formatTimeRemainingFunction = (timestamp: number) => {
  const seconds = Math.floor((timestamp / 1000) % 60)
  const minutes = Math.floor((timestamp / 1000 / 60) % 60)
  const hours = Math.floor((timestamp / (1000 * 60 * 60)) % 24)
  const days = Math.floor(timestamp / (1000 * 60 * 60 * 24))

  return { seconds, minutes, hours, days }
}
